package com.qf.blog.controller;

import com.qf.blog.commons.utils.EmailUtils;
import com.qf.blog.commons.utils.UUIDUtils;
import com.qf.blog.dto.EmailDto;
import com.qf.blog.service.UserService;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.Map;


@Controller
public class ResetPwdContrtller {
    @Autowired
    private UserService userService;
    @Autowired
    private EmailUtils emailUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/resetPwd")
    public String resetPwd() {
        return "site/reset-pwd";
    }
    @PostMapping("/reset")
    public String reset(@RequestParam Map<String, String> formData) {
        String email = formData.get("username");
        String kaptchaCode = formData.get("kaptchaCode");
        String emailVerifyCode = formData.get("emailVerifyCode");
        // 在这里进行重置密码的逻辑处理
        // ...
        Object body = redisTemplate.opsForValue().get("body");
        if (!emailVerifyCode.isEmpty()) {
            if (emailVerifyCode.equals(body)) {
                String dbPw = BCrypt.hashpw(emailVerifyCode,BCrypt.gensalt());
                if (userService.updeteUser(email,emailVerifyCode)){
                    return "redirect:user/login";
                }
            }
        }
        return null;
    }

    @RequestMapping("/sendEmailCodeForResetPwd")
    @ResponseBody
    public String sendEmailCodeForResetPwd(@RequestParam String username, @RequestParam String kaptcha) {
        if (!username.isEmpty() && !kaptcha.isEmpty()) {
            Object captchaText = redisTemplate.opsForValue().get("captchaText");
            if (captchaText.equals(kaptcha)) {
                String email = username;
                EmailDto emailDto = new EmailDto();
                String to = email;
                String subject = "66666";
                String body = UUIDUtils.getId().substring(0, 6);
                redisTemplate.opsForValue().set("body", body);
                emailDto.setTo(to);
                emailDto.setTitle(subject);
                emailDto.setContent(body);
                emailUtils.sendEmail(emailDto);
                userService.updateByEmail(email, body);
                return "验证成功";
            }
        }
        return null;
    }
}